<template>
  <!-- 订单列表 -->
  <scroll-view enable-back-to-top scroll-y class="orders" refresher-enabled :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh" @scrolltolower="getUserOrderData">
    <view class="card" v-for="order in orderList" :key="order.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[order.status].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text v-if="order.status === 4 || order.status === 5 || order.status === 6" class="icon-delete"
          @tap="onOrderDelete(order.id)"></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator v-for="sku in order.orderSkuVOList" :key="sku.itemId" class="goods"
        :url="`/pagesOrder/detail/detail?id=${order.id}`" hover-class="none">
        <view class="cover">
          <image mode="aspectFill" :style="{ width: '100%', height: '100%' }" :src="sku.image">
          </image>
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ sku.itemName }}</view>
          <view class="type">{{ sku.spec }}</view>
        </view>

      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalCount }}件商品</text>
        <text>实付</text>
        <text class="amount"> <text class="symbol">¥</text>{{ order.payMoney }}</text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="order.status === 1">
          <view class="button primary" @tap="onOrderPay(order.id)">去支付</view>
        </template>
        <template v-else>
          <navigator class="button secondary" :url="`/pagesOrder/create/create?skuId=${order.id}&count=${1}`"
            hover-class="none">
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view v-if="order.status === 3" @tap="onOrderConfirm(order.id)" class="button primary">确认收货</view>
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ isFinish ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import {
  getUserOrderListAPI,
  putUserOrderReceiptByIdAPI,
  deleteUserOrderByIdAPI
} from '@/services/order'
import { payAPI } from '@/services/pay'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const props = defineProps({
  orderState: Number
})

/** 订单状态列表 */
const orderStateList = ref([
  { id: 0, text: '' },
  { id: 1, text: '待付款' },
  { id: 2, text: '待发货' },
  { id: 3, text: '待收货' },
  { id: 4, text: '待评价' },
  { id: 5, text: '已完成' },
  { id: 6, text: '已取消' },
])

// 是否分页结束
const isFinish = ref(false)
// 是否触发下拉刷新
const isTriggered = ref(false)

//请求参数
const queryParams = ref({
  page: 1,
  pageSize: 5,
  status: props.orderState
})
// 获取订单列表
const orderList = ref([])

// 是否加载中标记，用于防止滚动触底触发多次请求
const isLoading = ref(false)
const getUserOrderData = async () => {
  // 如果数据处于加载中，退出函数
  if (isLoading.value) return
  // 退出分页判断
  if (isFinish.value === true) {
    return uni.showToast({ icon: 'none', title: '没有更多数据~' })
  }
  // 发送请求前，标记为加载中
  isLoading.value = true
  // 发送请求

  const res = await getUserOrderListAPI(queryParams.value)
  console.log('完整响应数据:', res)
  console.log('订单列表:', res.data.records)
  // 发送请求后，重置标记
  isLoading.value = false
  // 数组追加
  orderList.value.push(...res.data.records)
  // 分页条件
  if (res.data.records.length >= queryParams.value.pageSize) {

    // 页码累加
    queryParams.value.page++
  } else {
    // 分页已结束
    isFinish.value = true
  }
}

const onOrderPay = async (id) => {
  try {
    const order = orderList.value.find(item => item.id === id)
    if (!order) return

    const res = await payAPI({
      orderId: id,
      payType: 1,
      payMoney: order.payMoney,
      subject: '订单支付'
    })

    if (res.code === 1) {
      uni.redirectTo({
        url: `/pagesOrder/payment/payment?id=${id}`
      })
    }
  } catch (error) {
    uni.showToast({
      title: '支付失败',
      icon: 'none'
    })
  }
}

onMounted(() => {
  getUserOrderData()
})

// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置数据
  queryParams.value.page = 1
  orderList.value = []
  isFinish.value = false
  // 加载数据
  await getUserOrderData()
  // 关闭动画
  isTriggered.value = false
}

const onOrderConfirm = async (id) => {
  //确认收货吗？
  uni.showModal({
    title: '提示',
    content: '确定收货吗？',
    success: async (res) => {
      if (res.confirm) {
        // 确认收货
        await putUserOrderReceiptByIdAPI(id)
        // 更新订单状态
        const order = orderList.value.find(item => item.id === id)
        order.status = 4
        // 提示
        uni.showToast({
          title: '确认收货成功',
          icon: 'success'
        })
      }
    }
  })
}

//删除订单
const onOrderDelete = async (id) => {
  //二次确认
  uni.showModal({
    content: '确定删除订单吗？',
    success: async (success) => {
      if (success.confirm) {
        //删除
        await deleteUserOrderByIdAPI(id)
        // 从列表中移除该订单
        orderList.value = orderList.value.filter(item => item.id !== id)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    },
  })
}
</script>

<style lang="scss">
// 订单列表
.orders {
  height: 100%; // 添加这一行

  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

   .cover {
  width: 170rpx;
  height: 170rpx;
  margin-right: 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
  position: relative;

  image {
    width: 100%;
    height: 100%;
    object-fit: cover; // 使用 object-fit 来确保填满容器且不失真
  }
}

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;
    background-color: #f9f9f9;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
      font-weight: bold;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  // 正确闭合 .payment 样式块

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
